package com.beyond.pm.component

import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import com.beyond.pm.base.BasicViewModel
import com.beyond.pm.base.LoadUiIntent
import com.beyond.pm.local.LocalNavController
import com.beyond.pm.local.loadStatusState
import com.beyond.pm.local.snackStatusState
import kotlinx.coroutines.launch

/**
 * 实现抽取提示
 */
@Composable
fun <VM : BasicViewModel> BaseEventComponent(viewModel: VM, content: @Composable () -> Unit) {
    val snackBarHostState by snackStatusState
    val scope = rememberCoroutineScope()
    val isLoading = remember { loadStatusState }
    val nav = LocalNavController.current

    LaunchedEffect(Unit) {
        viewModel.loadUiIntentFlow.collect {
            when (it) {
                is LoadUiIntent.Error -> {
                    scope.launch {
                        snackBarHostState.currentSnackbarData?.dismiss()
                        snackBarHostState.showSnackbar(it.msg)
                    }
                }

                is LoadUiIntent.Loading -> {
                    isLoading.value = it.isShow
                }

                is LoadUiIntent.Route -> {
                    nav.navigate(it.page)
                }
            }
        }
    }
    content()
}